/*
 * timer.c
 *
 *  Created on: 2010-12-05
 *      Author: Piotrek
 */
#include <inttypes.h>
#include <avr/io.h>
#include <avr/eeprom.h>
#include "timer.h"

extern struct timer* timers[TIMER_COUNT];
extern uint8_t powerStatus[TIMER_COUNT];

void readTimer(struct timer *timer) {
	register uint8_t addr = 0;
	addr = TIMER_COUNT + (timer->id * 4);
	timer->hour_on = eeprom_read_byte((uint8_t*) addr++);
	timer->min_on = eeprom_read_byte((uint8_t*) addr++);
	timer->hour_off = eeprom_read_byte((uint8_t*) addr++);
	timer->min_off = eeprom_read_byte((uint8_t*) addr);
}

void writeTimer(struct timer *timer) {
	register uint8_t addr = 0;
	addr = TIMER_COUNT + (timer->id * 4);
	eeprom_write_byte((uint8_t*) addr++, timer->hour_on);
	eeprom_write_byte((uint8_t*) addr++, timer->min_on);
	eeprom_write_byte((uint8_t*) addr++, timer->hour_off);
	eeprom_write_byte((uint8_t*) addr, timer->min_off);
}

void powerOn(uint8_t id) {
	powerStatus[id] = 1;
	POWER_PORT |= _BV(id);
}

void powerOff(uint8_t id) {
	powerStatus[id] = 0;
	POWER_PORT &= ~_BV(id);
}

uint8_t getPowerStatus(uint8_t id) {
	return powerStatus[id];
}

void checkTimers(unsigned char hour, unsigned char min) {
	int i = 0;
	for (i = 0; i < TIMER_COUNT; i++) {
		if (hour == timers[i]->hour_on) {
			if (min == timers[i]->min_on) {
				powerOn(timers[i]->id);
			}
		} else if (hour == timers[i]->hour_off) {
			if (min == timers[i]->min_off) {
				powerOff(timers[i]->id);
			}
		}
	}
}
